import axios from 'axios';

const URL = 'http://qt.gtimg.cn/q=';

export type CompanyPriceValue = {
    code: string;
    price: number;
    value: number;
}

export function getPriceAndValue(codes: string[]) {
    if (codes == null || codes.length === 0) return [];
    const codeList = codes.reduce((prev, code) => `${prev}s_${code},`, '');
    return axios.get(`${URL}${codeList}`).then((response) => {
        if (response.status === 200) {
            return response.data
                .split(';')
                .filter((data: string) => data.length > 0 && data.includes('='))
                .map((data: string) => {
                    let [codeString, dataString] = data.split('=');
                    codeString = codeString.replace('\n', '');
                    const dataArray = dataString.split('~');
                    if (codeString.length < 5 || dataArray.length < 10) {
                        return {};
                    }
                    return {
                        code: codeString.substring(4),
                        price: parseFloat(dataArray[3]),
                        value: parseFloat(dataArray[9]),
                    };
                });
        }
        return Promise.reject(new Error(`status ${response.status}`));
    });
}
